const express = require('express');
const router = express.Router();
const validationService = require('../services/validation.service');

// 手动触发验证（用于测试）
router.post('/trigger', async (req, res, next) => {
  try {
    const { phones } = req.body;
    const maxConcurrency = parseInt(process.env.MAX_CONCURRENCY);
    
    if (!phones || !Array.isArray(phones) || phones.length === 0) {
      return res.status(400).json({ success: false, message: '请提供有效的手机号码数组' });
    }
    
    const uploadId = require('uuid').v4();
    
    validationService.startValidation(phones, uploadId, maxConcurrency)
      .catch(err => console.error(`验证过程出错: ${err.message}`));
    
    res.json({
      success: true,
      uploadId,
      message: '验证已开始',
      phoneCount: phones.length
    });
  } catch (error) {
    next(error);
  }
});

// 获取验证结果
router.get('/result/:uploadId', async (req, res, next) => {
  try {
    const { uploadId } = req.params;
    const result = await validationService.getValidationResult(uploadId);
    
    if (!result) {
      return res.status(404).json({ success: false, message: '验证结果不存在或尚未完成' });
    }
    
    res.json({
      success: true,
      uploadId,
      result
    });
  } catch (error) {
    next(error);
  }
});

module.exports = router;
